'''
Created on 29.07.2010

@author: Valiuh Anton - valiuh@gmail.com
'''

import Image
import ImageDraw

class FindFaces(object):
    '''
    This class using for find face in input YCbCr image.
        Then coordinates which was found in YCbCr image by 
        color histograms will be used to draw an ellipse 
        around face in input RGB image. 
        CalcHists() - procedure for calculation X(width) and 
            Y(height) distributions of white component in 
            input grey scale image
        Face() - procedure for finding center of ellipse - max 
            value in X(width) and Y(height) distributions. And 
            than it draw an ellipse around face in input RGB image 
        imageCbCr - copy of input grey scale image
        image - copy of input RGB image
        width_hist - X(width) distributions of white component
        height_hist - Y(height) distributions of white component   
           
    '''
#==================================================================
    def __init__(self, imageCbCr,image):
        '''
        Constructor
        '''
        self.imageCbCr = imageCbCr
        self.image = image
        self.width_hist=[]
        self.height_hist=[]
        print "\t==== class FindFaces init ok ====" 
#==================================================================   
    def CalcHists(self):
        '''
            Calculation X(width) and Y(height) distributions 
            of white component in input grey scale image.
        '''
        width, height = self.imageCbCr.size
        count = 0
        for i in range(height):
            for j in range (width):
                rgb = self.imageCbCr.getpixel((j,i))
                if rgb==255:
                    count=count+1
            self.height_hist.append(count)
            count = 0
            
        count = 0
        for i in range(width):
            for j in range (height):
                rgb = self.imageCbCr.getpixel((i,j))
                if rgb==255:
                    count=count+1
            self.width_hist.append(count)
            count = 0
#=====================================================================    
    def Face(self):
        
        '''
            Finding center of ellipse - max value in X(width) 
            and Y(height) distributions. And than it draw an 
            ellipse around face in input RGB image.
        '''
               
        self.CalcHists()
               
        y=self.height_hist.index(max(self.height_hist))
        x=self.width_hist.index(max(self.width_hist))
        
        draw = ImageDraw.Draw(self.image)
        draw.ellipse((x-20,y-20,x+20,y+20), None, "blue")
                
        self.image.show()
        self.image.save("result.jpg", "JPEG")  
        
        
        